package io.lckgroup.modules.lck.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.lckgroup.common.exception.BackException;
import io.lckgroup.common.utils.PageUtils;
import io.lckgroup.common.utils.Query;
import io.lckgroup.modules.lck.dao.CommonAdDao;
import io.lckgroup.modules.lck.dao.MerchantUserDao;
import io.lckgroup.modules.lck.dao.ShopMerchantInfoDao;
import io.lckgroup.modules.lck.entity.CommonAdEntity;
import io.lckgroup.modules.lck.entity.MerchantUserEntity;
import io.lckgroup.modules.lck.entity.ShopMerchantInfoEntity;
import io.lckgroup.modules.lck.form.ShopMerchantUserForm;
import io.lckgroup.modules.lck.form.wxgzh.Gps;
import io.lckgroup.modules.lck.service.ShopMerchantInfoService;
import io.lckgroup.modules.lck.utils.PositionUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;


@Service("shopMerchantInfoService")
public class ShopMerchantInfoServiceImpl extends ServiceImpl<ShopMerchantInfoDao, ShopMerchantInfoEntity> implements ShopMerchantInfoService {

    @Autowired
    private MerchantUserDao merchantUserDao;

    @Autowired
    private ShopMerchantInfoDao shopMerchantInfoDao;

    @Autowired
    private CommonAdDao commonAdDao;
    private Logger logger = LoggerFactory.getLogger(getClass());


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<ShopMerchantInfoEntity> page = this.page(
                new Query<ShopMerchantInfoEntity>().getPage(params),
                new QueryWrapper<ShopMerchantInfoEntity>().eq("is_delete", 0)
                //.eq("is_open",1)
        );
        return new PageUtils(page);
    }

    @Transactional
    @Override
    @Cacheable(value = "queryPageByShopMerchantInfoCache", key = "#params.get(\"redis\")") //存方法返回值
    public PageUtils queryPageByShopMerchantInfoEntity(@RequestParam Map<String, Object> params) {
        if (params.containsKey("merchantName")) {
            String merchantName = params.get("merchantName").toString();
            if (!merchantName.equals("")) {
                ShopMerchantInfoEntity shopMerchantInfoEntity = new ShopMerchantInfoEntity();
                shopMerchantInfoEntity.setMerchantName(merchantName);
                IPage<ShopMerchantInfoEntity> page = this.page(
                        new Query<ShopMerchantInfoEntity>().getPage(params),
                        new QueryWrapper<ShopMerchantInfoEntity>().eq("is_delete", 0).like("merchant_name", shopMerchantInfoEntity.getMerchantName())
                );
                return new PageUtils(page);
            } else {
                return queryPage(params);
            }
        } else {
            return queryPage(params);
        }
    }


    /**
     * 保存商家信息和用户信息
     *
     * @param shopMerchantUser
     */
    @Transactional
    @Override
    @CacheEvict(value = "queryPageByShopMerchantInfoCache", allEntries = true)
    public void saveUser(ShopMerchantUserForm shopMerchantUser) {
        //用户
        MerchantUserEntity user = new MerchantUserEntity();
        user.setMobile(shopMerchantUser.getTelphone());
        QueryWrapper<MerchantUserEntity> wrapper1=new QueryWrapper<>();
        wrapper1.setEntity(user);
        //手机号条数
        int count1 = merchantUserDao.selectCount(wrapper1);
        ShopMerchantInfoEntity shopMerchantInfoEntity = new ShopMerchantInfoEntity();
        shopMerchantInfoEntity.setMerchantNo(shopMerchantUser.getMerchantNo());
        QueryWrapper<ShopMerchantInfoEntity> wrapper=new QueryWrapper<>();
        wrapper.setEntity(shopMerchantInfoEntity);
        //商户号条数
        int count = shopMerchantInfoDao.selectCount(wrapper);
        if(count1==0&&count==0){
            shopMerchantUser.setUserId(user.getUserId());
            shopMerchantUser.setCommentNum(0);
            shopMerchantUser.setScore(new BigDecimal(0));
            //wei
            Double latitude=shopMerchantUser.getLatitude().doubleValue();
            //jin
            Double longitude=shopMerchantUser.getLongitude().doubleValue();
            Gps gps=PositionUtil.bd09_To_Gcj02(latitude,longitude);
            BigDecimal Latitudes=new BigDecimal(gps.getWgLat());
            BigDecimal Longitude=new BigDecimal(gps.getWgLon());
//            System.out.println("latitude:"+latitude+"longitude"+longitude);
//            System.out.println("gps:"+gps+"  "+gps.getWgLat()+gps.getWgLon());
            shopMerchantUser.setLatitude(Latitudes);
            shopMerchantUser.setLongitude(Longitude);

            shopMerchantInfoDao.insert(shopMerchantUser);
            user.setUsername(shopMerchantUser.getLeaderName());
            user.setPassword(DigestUtils.sha256Hex(shopMerchantUser.getPassword()));
            merchantUserDao.insert(user);
        }else if(count1>0&&count==0){
            throw new BackException("手机号已经已存在", 500);
        }else if(count>0&&count1==0){
            throw new BackException("商户号已经已存在", 500);
        }else {
            throw new BackException("手机号,商户号已经已存在", 500);
        }
//        //商家信息  添加之前需要查询商户号 （是否唯一）
//        System.out.println("count:"+count);
//        System.out.println("count1:"+count1);
    }

    /**
     * 功能描述: <br>
     * 〈〉根据id查询商户信息
     *
     * @Param: [merchantInfoEntity]
     * @Return: io.lckgroup.modules.lck.entity.ShopMerchantInfoEntity
     * @Author: 13980
     * @Date: 2020/3/6 10:47
     */
    @Override
    public ShopMerchantInfoEntity getMerchantinfo(ShopMerchantInfoEntity merchantInfoEntity) {
        QueryWrapper<ShopMerchantInfoEntity> wrapper = new QueryWrapper<>();
        wrapper.setEntity(merchantInfoEntity);
        ShopMerchantInfoEntity entity = shopMerchantInfoDao.selectOne(wrapper);
        return entity;
    }

    @Override
    public void BatchDelete(Long[] ids) {
        shopMerchantInfoDao.BatchDeleteShopMerchantInfo(ids);
    }

    @Override
    public CommonAdEntity getAd() {
        return commonAdDao.selectOne(new QueryWrapper<>());
    }

    @Override
    public PageUtils getShopMerchantByCondition(Map<String, Object> params) {
        //分页参数
        Page page = new Page<>(Integer.valueOf(params.get("page").toString()), Integer.valueOf(params.get("limit").toString()));
        //排序参数
        String condition = params.get("condition").toString();
        String latitude = params.get("latitude").toString();
        String longitude = params.get("longitude").toString();
        IPage<ShopMerchantInfoEntity> iPage = shopMerchantInfoDao.getShopMerchantByCondition(page, condition,longitude,latitude);
        return new PageUtils(iPage);
    }
    @Override
    public Long[] selectMerchantInfoByMonth(Map<String, Object> params) {
        String year = params.get("year").toString();
        int years = Integer.parseInt(year);
        String gmtCreate =year+"-"+"01-01 00:00:00";
        String gmtCreates =(years+1)+"-"+"01-01 00:00:00";
        List<Map<String,String>> list=shopMerchantInfoDao.selectMerchantInfoByMonth(gmtCreate,gmtCreates);
        Long[] num = new Long[12];
        for (int i = 0; i <12 ; i++) {
            num[i]=0L;
        }
        for (int i = 0; i <list.size(); i++) {
            int index = Integer.parseInt(String.valueOf(list.get(i).get("month")))-1 ;
            num[index]=Long.parseLong(String.valueOf(list.get(i).get("MerchantNum")));
        }
        return num;
    }

    @Override
    public PageUtils getShopMerchantByConditionAndSearch(Map<String, Object> params) {
        //分页参数
        Page page = new Page<>(Integer.valueOf(params.get("page").toString()), Integer.valueOf(params.get("limit").toString()));
        //排序参数
        String condition = params.get("condition").toString();
        String latitude = params.get("latitude").toString();
        String longitude = params.get("longitude").toString();
        //搜索条件
        String search = params.get("search").toString();
        IPage<ShopMerchantInfoEntity> iPage = shopMerchantInfoDao.getShopMerchantByConditionAndSearch(page, condition,longitude,latitude,search);
        return new PageUtils(iPage);
    }

    @Override
    public List<ShopMerchantInfoEntity> getAllMerchantInfo() {
        logger.info("查询商家信息");
        QueryWrapper<ShopMerchantInfoEntity> queryWrapper = new QueryWrapper<>();
        List<ShopMerchantInfoEntity> list = baseMapper.selectList(queryWrapper);
        logger.info("查询所有商家返回值"+list);
        return list;
    }

}